<template>
  <!-- eslint-disable vue/no-use-v-if-with-v-for,vue/no-confusing-v-for-v-if -->
  <div>
    <el-container>
      <el-header class="homeHeader">
        <div class="title">小邮社区交流系统</div>
        <el-dropdown class="userInfo" @command="commandHandler">
          <span style="color:#303133">
            {{ user.username }}<i><img class="el-dropdown-link" :src="user.userFace" /></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="userInfo">个人中心</el-dropdown-item>
            <el-dropdown-item command="setting">设置</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu router unique-opened>
            <el-submenu
              :index="index + ''"
              v-for="(item, index) in routes"
              v-if="!item.hidden"
              :key="index"
            >
              <template slot="title"
                ><i
                  :class="iconfont+item.iconCls"
                  style="color: rgb(13 13 13); margin-right: 5px"
                ></i>
                <span>{{ item.name }}</span></template
              >
              <el-menu-item
                :index="children.path"
                v-for="(children, indexj) in item.children"
                :key="indexj"
                >{{ children.name }}
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-aside>
        <el-main>
          <el-breadcrumb
            separator-class="el-icon-arrow-right"
            v-if="this.$router.currentRoute.path !== '/home'">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{
              this.$router.currentRoute.name
            }}</el-breadcrumb-item>
          </el-breadcrumb>
          <div 
            v-if="this.$router.currentRoute.path == '/home'">
            <div>
              <div
                v-clickoutside="hideReplyBtn"
                @click="inputFocus"
                class="my-reply">
                <el-avatar
                  class="header-img"
                  :size="40"
                  :src="user.userFace">
                </el-avatar>
                <div class="reply-info">
                  <div
                    tabindex="0"
                    contenteditable="true"
                    id="replyInput"
                    spellcheck="false"
                    placeholder="输入评论..."
                    class="reply-input"
                    @focus="showReplyBtn"
                    @input="onDivInput($event)">
                  </div>
                </div>
                <div class="reply-btn-box" v-show="btnShow">
                <el-button
                  class="reply-btn"
                  size="medium"
                  @click="sendComment"
                  type="primary">发表评论</el-button>
                </div>
              </div>
              <ul v-infinite-scroll="load">
                <li>
                  <div               
                    v-for="(item, i) in comments"
                    :key="i"
                    class="author-title reply-father">
                    <el-avatar
                      class="header-img"
                      :size="40"
                      :src="item.userInfo.userFace"
                    ></el-avatar>
                    <div class="author-info">
                      <span class="author-name">{{ item.userInfo.username }}</span>
                      <span class="author-time">{{ item.dateTime }}</span>
                    </div>
                                  
                    <div class="talk-box">
                      <p>
                        <span class="reply">{{ item.content }}</span>
                      </p>
                    </div>
                    <div class="icon-btn">
                      <span class="shareComment"><i class="iconfont icon-fenxiang"></i></span>
                      
                      <span @click="showReplyInput(i, item.userInfo.username, item.topicId, item.topicType)" class="iconComment">
                        <i class="iconfont icon-pinglun"></i
                        >{{ item.replyCount }}</span>
                      
                      <span @click="dianzanComment(i,item.topicId)" class="dianzanComment">
                        <i class="iconfont icon-dianzan"></i>{{ item.greatCount }}</span>
                    </div>
                    <el-divider></el-divider>
                    
                    <div id="replybox" v-clickoutside="hedeReplybox">
                        <div class="reply-box" v-show="_replyShow(i)">
                          <div
                          v-for="(reply, j) in item.reply"
                          :key="j"
                          class="author-title">
                          <el-avatar
                            class="header-img"
                            :size="40"
                            :src="reply.userInfo.userFace"
                          ></el-avatar>
                          <div class="author-info">
                            <span class="author-name">{{ reply.userInfo.username }}</span>
                            <span class="author-time">{{ reply.dateTime }}</span>
                          </div>
                          <!-- <div class="icon-btn-reply">
                            <span @click="showReplyInput(i, reply.from, item.topicId, item.topicType)"
                              ><i class="iconfont icon-pinglun"></i
                              >{{ reply.count }}</span>
                            <i class="iconfont icon-dianzan"></i>{{ reply.greatCount }}
                          </div> -->
                          <div class="talk-box">
                            <p>
                              <span>回复 </span><span style="color:blue">{{ item.userInfo.username }}: </span>
                              <span class="reply">{{ reply.content }}</span>
                            </p>
                          </div>
                          
                        </div>
                      </div>
                      
                      <div v-show="_inputShow(i)" class="my-reply my-comment-reply">
                        <el-avatar
                          class="header-img"
                          :size="40"
                          :src="user.userFace"
                        ></el-avatar>
                        <div class="reply-info">
                          <div
                            tabindex="0"
                            contenteditable="true"
                            spellcheck="false"
                            placeholder="输入回复..."
                            @input="onDivInput($event)"
                            class="reply-input reply-comment-input"
                          ></div>
                        </div>
                        <div class="reply-btn-box">
                          <el-button
                            class="reply-btn"
                            size="medium"
                            @click="sendCommentReply(i, item.topicId, item.fromUid, item.topicType)"
                            type="primary">发表回复</el-button>
                        </div>
                      </div>
                    </div>               
                  </div>
                </li>
              </ul>
              
            </div>
          </div>
          <router-view class="homeRouterView"/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
const clickoutside = {
    // 初始化指令
    bind(el, binding, vnode) {
        function documentHandler(e) {
            // 这里判断点击的元素是否是本身，是本身，则返回
            if (el.contains(e.target)) {
                return false;
            }
            // 判断指令中是否绑定了函数
            if (binding.expression) {
                // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
                binding.value(e);
            }
        }
        // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
        el.__vueClickOutside__ = documentHandler;
        document.addEventListener('click', documentHandler);
    },
    update() {},
    unbind(el, binding) {
        // 解除事件监听
        document.removeEventListener('click', el.__vueClickOutside__);
        delete el.__vueClickOutside__;
    },
};
export default {
  name: "Home",
  computed: {
    routes() {
      return this.$store.state.routes;
    },
  },
  data() {
    return {
      pageNum: 0,
      pageSize: 0,
      size: 0,
      pages: 0,
      prePage: 0,
      nextPage: 0,
      isFirstPage: false,
      isLastPage: false,
      hasPreviousPage: false,
      hasNextPage: false,
      navigatePages: 0,
      navigatePageNum: [],
      navigateFirstPage: 0,
      navigateLastPage: 0,

      loading: false,
      inputShow: false,
      iconfont:'iconfont ',
      btnShow: false,
      index: "0",
      replyComment: "",
      myName: "Lana Del Rey",
      myHeader:"",
      myId: 19870621,
      to: "",
      toId: -1,
      
      comments: [
        {
          reply: [],
          replyCount: 0,
          topicId:'',
          topicType: '',
          fromId: '',
          greatCount: '',
          dateTime: '',         
          userInfo: {
            userId: '',
            username: '',
            stuId: '',
            sex: '',
            age: '',
            userFace: '',
          },
        },
      ],

      user: JSON.parse(window.sessionStorage.getItem("user")),
      item: "",
      replyShow: false
    };
  },
  directives: { clickoutside },
  mounted() {
    this.initcomment(1);
  },
  methods: {
    load() {
      let pageIndex = 1;
      // this.initcomment(++pageIndex);
    },
    initcomment(pageIndex) {
      console.log(pageIndex)
      this.getRequest('/comment/queryCommentByPage?pageIndex='+pageIndex).then((resp) => {
        if(resp) {
          let page = resp.obj;
          this.pageNum = page.pageNum;
          this.comments = page.list;
          this.size = page.size;
          this.pages = page.pages;
          this.prePage = page.prePage;
          this.nextPage = page.nextPage;
          this.isFirstPage = page.isFirstPage;
          this.isLastPage = page.isLastPage;
          this.hasPreviousPage = page.hasPreviousPage;
          this.hasNextPage = page.hasNextPage;
          this.navigatePages = page.navigatePages;
          this.navigatePageNum = page.navigatePageNums;
          this.navigateFirstPage = page.navigateFirstPage;
          this.navigateLastPage = page.navigateLastPage;
          console.log(this.pages)
        }
      })
    },
    inputFocus() {
      var replyInput = document.getElementById("replyInput");
      replyInput.style.padding = "8px 8px";
      replyInput.style.border = "2px solid blue";
      replyInput.focus();
    },
    showReplyBtn() {
      this.btnShow = true;
    },
    hideReplyBtn() {
      this.btnShow = false;
      replyInput.style.padding = "10px";
      replyInput.style.border = "none";
    },
    hedeReplybox(e) {
      // console.log("===========")
      // let replybox = document.getElementById("replybox");
      // replybox.style.display="none";
    },
    showReplyInput(i, name, topicId, topicType) {
      let page = 1;
      this.getRequest('/reply/getReplyById?id='+topicId+'&topicType='+topicType+'&currentPage='+page).then((resp) => {
        if (resp) {         
          this.comments.reply=resp;
          console.log(this.reply);
        }
      });
      // this.comments[this.index].inputShow = false;
      // this.index = i;
      console.log(i)
      this.comments[i].replyShow = !this.comments[i].replyShow;
      this.comments[i].inputShow = !this.comments[i].inputShow;
      // this.to = name;
      // this.toId = topicId;
    },
    showReply() {
      return true;
    },
    _replyShow(i) {
      return this.comments[i].replyShow;
    },
    _inputShow(i) {
      return this.comments[i].inputShow;
    },
    dianzanComment(i,topicId) {
        this.postRequest("/comment/updateGreatCount",topicId).then((resp) => {
          if (resp) {
            this.comments[i].greatCount++;
          }
        })
    },
    sendComment() {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "评论不能为空",
        });
      } else {
        let input = document.getElementById("replyInput");
        var x=input.innerHTML
        console.log(x)
        this.postRequest("/comment/postComment",input.innerHTML).then((resp)=>{
          if (resp) {
            this.initcomment(1);
            // location.reload();
          }
        })
        // let a = {};
        // let input = document.getElementById("replyInput");
        // let timeNow = new Date().getTime();
        // let time = this.dateStr(timeNow);
        // a.name = this.myName;
        // a.comment = this.replyComment;
        // a.headImg = this.myHeader;
        // a.time = time;
        // a.commentNum = 0;
        // a.like = 0;
        // this.comments.push(a);
        // this.replyComment = "";
        // input.innerHTML = "";
      }
    },
    sendCommentReply(i, topicId, toUid, topicType) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "回复不能为空",
        });
      } else {       
        let params = {
          content: document.getElementsByClassName("reply-comment-input")[i].innerHTML,
          id: topicId,
          toUid: toUid,
          topicType: 'comment'
        };
        this.postRequest("/reply/postReply",params).then((resp)=>{
          if (resp) {
            location.reload();
          }
        })

        // let a = {};
        // let timeNow = new Date().getTime();
        // let time = this.dateStr(timeNow);
        // a.from = this.myName;
        // a.to = this.to;
        // a.fromHeadImg = this.myHeader;
        // a.comment = this.replyComment;
        // a.time = time;
        // a.commentNum = 0;
        // a.like = 0;
        // this.comments[i].reply.push(a);
        // this.replyComment = "";
        // document.getElementsByClassName("reply-comment-input")[i].innerHTML =
        //   "";
      }
    },
    onDivInput: function (e) {
      this.replyComment = e.target.innerHTML;
    },
    dateStr(date) {
      //获取js 时间戳
      var time = new Date().getTime();
      //去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000);
      //存储转换值
      var s;
      if (time < 60 * 10) {
        //十分钟内
        return "刚刚";
      } else if (time < 60 * 60 && time >= 60 * 10) {
        //超过十分钟少于1小时
        s = Math.floor(time / 60);
        return s + "分钟前";
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        //超过1小时少于24小时
        s = Math.floor(time / 60 / 60);
        return s + "小时前";
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        //超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24);
        return s + "天前";
      } else {
        //超过30天ddd
        var date = new Date(parseInt(date));
        return (
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate()
        );
      }
    },

    commandHandler(command) {
      if (command == "logout") {
        this.$confirm("此操作将退出登录，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //注销登录
            this.postRequest("/logout");
            console.log("注销请求");
            //清空用户信息
            window.sessionStorage.removeItem("tokenStr");
            window.sessionStorage.removeItem("user");
            //清空菜单
            this.$store.commit("initRoutes", []);
            //跳转登录页面
            this.$router.replace("/");
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消退出",
            });
          });
      };
      if (command == "userInfo") {
        this.$router.push('/userInfo')
      };
      if (command == "setting") {
        this.$router.push('/setting')
      }
    },
  },
};
</script>

<style>
.my-reply {
  padding: 10px;
  background-color: #fafbfc;
}
.my-reply .header-img {
  display: inline-block;
  vertical-align: top;
}
.my-reply .reply-info {
  display: inline-block;
  margin-left: 5px;
  width: 90%;
}
@media screen and (max-width: 1200px) {
  .my-reply .reply-info {
    width: 80%;
  }
}
.my-reply .reply-info .reply-input {
  min-height: 20px;
  line-height: 50px;
  padding: 10px 10px;
  color: #040608;
  background-color: #fff;
  border-radius: 5px;
}
.my-reply .reply-info .reply-input:empty:before {
  content: attr(placeholder);
}
.my-reply .reply-info .reply-input:focus:before {
  content: none;
}
.my-reply .reply-info .reply-input:focus {
  padding: 8px 8px;
  border: 2px solid #00f;
  box-shadow: none;
  outline: none;
}
.my-reply .reply-btn-box {
  height: 25px;
  margin: 10px 0;
}
.my-reply .reply-btn-box .reply-btn {
  position: relative;
  float: right;
  margin-right: 15px;
}
.my-comment-reply {
  margin-left: 50px;
}
.my-comment-reply .reply-input {
  width: flex;
}

.author-title {
  padding: 10px;
}
.author-title .header-img {
  display: inline-block;
  vertical-align: top;
}
.author-title .author-info {
  display: inline-block;
  margin-left: 5px;
  width: 60%;
  height: 40px;
  line-height: 20px;
}
.author-title .author-info > span {
  display: block;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.author-title .author-info .author-name {
  color: #000;
  font-size: 18px;
  font-weight: bold;
}
.author-title .author-info .author-time {
  font-size: 14px;
}
.author-title .icon-btn {
  width: 95%;
  padding: 0 !important;
  float: right;
  margin-top: 5px;
}
.icon-btn-reply{
  width: 30%;
  padding: 0 !important;
  float: right;
}
@media screen and (max-width: 1200px) {
  .author-title .icon-btn {
    width: 20%;
    padding: 7px;
  }
}
.author-title .icon-btn > span {
  cursor: pointer;
}
.author-title .icon-btn .iconfont {
  margin: 0 5px;
}
.author-title .talk-box {
  margin: 0 50px;
}
.author-title .talk-box > p {
  margin: 0;
}
.author-title .talk-box .reply {
  font-size: 16px;
  color: #000;
}
.author-title .reply-box {
  margin: 10px 0 0 50px;
  background-color: #efefef;
}

.homeHeader {
  background: rgb(14, 134, 158);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  box-sizing: border-box;
}
.homeHeader .title {
  font-size: 30px;
  font-family: 楷体;
  color: rgb(39, 48, 138);
  margin: 0 auto;
}
.homeHeader.userInfo {
  cursor: pointer;
}
.el-dropdown-link {
  width: 48px;
  height: 48px;
  border-radius: 24px;
  margin-left: 12px;
}
.homeRouterView {
  margin-top: 10px;
}
.iconComment {
  margin-left: 70px;
}
.shareComment {
  margin-right: 200px;
} 
.dianzanComment {
  margin-left: 300px;
}
</style>